package ink.tiptop.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ink.tiptop.common.domain.req.PageRequest;
import ink.tiptop.common.domain.rsp.PageResponse;
import ink.tiptop.common.domain.rsp.Response;
import ink.tiptop.utils.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author ink.tiptop.zjf
 * @Title: Ticket
 * @Package ink.tiptop.service.impl
 * @Description: 通用的部分
 * @date 2020-07-19 21:22
 */
@Slf4j
public abstract class AbstractBaseService<E> {

    /**
     * name desc
     */
    protected static final String ORDER_BY_FORMAT = "`%s` %s";

    /**
     * 通用列表查询部分
     *
     * @param request
     * @return
     */
    public Response list(PageRequest request) {
        log.info("通用列表的分页查询,request:{}", JSON.toJSONString(request));
        // 获取查询参数
        Object param = getQueryParam(request);
        // 设置分页参数
        setOrderBy(request);
        Integer currPage = request.getOffset()/request.getCapacity() +1;
        Page<E> ePage = new Page<>(currPage, request.getCapacity(), true);
        Page<E> pageInfo = getQueryEntityList(ePage, (E) param);
        // 组装响应参数,list
        Object responseList = getResponseList(pageInfo.getRecords());

        return new PageResponse((List) responseList)
                .total(pageInfo.getTotal())
                .offset(request.getOffset());
    }

    protected abstract void setOrderBy(PageRequest request);

    /**
     * 获取查询参数
     *
     * @param request
     * @return
     */
    protected abstract E getQueryParam(PageRequest request);

    /**
     * 获取查询到的数据集合
     *
     * @param param
     * @return
     * @Desc 这个方法不能加缓存, 因为分页查询入侵了代码, 会导致封装不到count数据
     */
    protected abstract Page<E> getQueryEntityList(Page<E> page, E param);

    /**
     * getQueryEntityList
     * 组装响应的list, entity -> vo,vo可以自定义
     *
     * @param voList
     * @return
     */
    protected abstract Object getResponseList(List<E> voList);

}
